<template>
  <div class="api-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>API配置管理</span>
          <div class="header-actions">
            <el-tag :type="activeConfigs > 0 ? 'success' : 'danger'" size="small">
              {{ activeConfigs > 0 ? `${activeConfigs}个配置可用` : '无可用配置' }}
            </el-tag>
            <el-button type="primary" size="small" @click="addNewConfig">
              <el-icon><Plus /></el-icon>
              新增配置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 配置列表 -->
      <div class="config-list" v-if="apiConfigs.length > 0">
        <el-card
          v-for="config in apiConfigs"
          :key="config.id"
          class="config-item"
          :class="{
            'disabled': !config.enabled
          }"
          shadow="hover"
        >
          <el-row :gutter="16" type="flex" justify="space-between" align="top">
            <el-col :span="16">
              <div class="config-info">
                <div class="config-name">
                  <span>{{ config.name }}</span>
                  <el-tag v-if="!config.enabled" type="info" size="small" style="margin-left: 8px;">已禁用</el-tag>
                </div>
                <div class="config-description">{{ config.description || '暂无描述' }}</div>
                <el-row :gutter="16" class="config-details">
                  <el-col :span="12">
                    <div class="config-detail-item">
                      <span class="label">模型:</span>
                      <span class="value">{{ config.selectedModel || '未设置' }}</span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="config-detail-item">
                      <span class="label">API地址:</span>
                      <span class="value">{{ config.baseUrl || '未设置' }}</span>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="config-actions">
                <!-- <el-button
                  v-if="config.enabled"
                  type="primary"
                  size="small"
                  @click="useConfig(config.id)"
                >
                  使用
                </el-button> -->
                <el-button
                  :type="config.enabled ? 'warning' : 'success'"
                  size="small"
                  @click="toggleConfigStatus(config)"
                >
                  {{ config.enabled ? '禁用' : '启用' }}
                </el-button>
                <el-button
                  type="warning"
                  size="small"
                  @click="testConnection(config)"
                  :loading="config.testing"
                >
                  测试连接
                </el-button>
                <el-button
                  size="small"
                  @click="editConfig(config)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  @click="duplicateConfig(config.id)"
                >
                  复制
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteConfig(config.id)"
                >
                  删除
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无API配置">
          <el-button type="primary" @click="addNewConfig">创建第一个配置</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 配置编辑对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="isEditing ? '编辑配置' : '新增配置'"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入配置名称" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="configForm.description"
            type="textarea"
            placeholder="请输入配置描述（可选）"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="API密钥" prop="apiKey">
          <el-input
            v-model="configForm.apiKey"
            type="password"
            placeholder="请输入API密钥"
            show-password
          />
        </el-form-item>

        <el-form-item label="API地址" prop="baseUrl">
          <el-input
            v-model="configForm.baseUrl"
            placeholder="https://api.openai.com/v1"
          />
        </el-form-item>

        <el-form-item label="模型">
          <el-select
            v-model="configForm.selectedModel"
            placeholder="选择模型"
            filterable
            allow-create
            style="width: 100%"
          >
            <el-option
              v-for="model in availableModels"
              :key="model.id"
              :label="model.name"
              :value="model.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="最大Token">
          <div class="max-tokens-control">
            <el-checkbox v-model="configForm.unlimitedTokens" @change="handleUnlimitedTokensChange">
              无限制Token
            </el-checkbox>
            <el-input-number
              v-if="!configForm.unlimitedTokens"
              v-model="configForm.maxTokens"
              :min="1"
              :max="10000000"
              :step="1000"
              style="width: 100%; margin-top: 8px;"
            />
          </div>
        </el-form-item>

        <el-form-item label="创造性">
          <el-slider
            v-model="configForm.temperature"
            :min="0"
            :max="1"
            :step="0.1"
            :format-tooltip="formatTemperature"
            show-tooltip
          />
        </el-form-item>

        <!-- <el-form-item label="设置">
          <el-checkbox v-model="configForm.isDefault">设为默认配置</el-checkbox>
          <el-checkbox v-model="configForm.enabled">启用此配置</el-checkbox>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <el-button @click="showConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfig" :loading="saving">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { apiConfigApi } from '../services/apiConfigApi.js'
import { useNovelStore } from '../stores/novel.js'

const store = useNovelStore()

// 响应式数据
const apiConfigs = ref([])
const showConfigDialog = ref(false)
const isEditing = ref(false)
const saving = ref(false)
const configFormRef = ref(null)

// 配置表单
const configForm = reactive({
  id: null,
  name: '',
  description: '',
  type: 'custom',
  apiKey: '',
  baseUrl: 'https://api.openai.com/v1',
  selectedModel: 'gpt-3.5-turbo',
  maxTokens: 2000000,
  unlimitedTokens: false,
  temperature: 0.7,
  topP: 1.0,
  frequencyPenalty: 0.0,
  presencePenalty: 0.0,
  timeout: 30,
  streamMode: true,
  retryCount: 3,
  customHeaders: '',
  enabled: true
})

// 表单验证规则
const configRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' }
  ],
  baseUrl: [
    { required: true, message: '请输入API地址', trigger: 'blur' }
  ]
}

// 可选模型
const defaultModels = [
  {
    id: 'deepseek-reasoner',
    name: 'deepseek-r1',
    description: 'deepseek-r1'
  },
  {
    id: 'deepseek-chat',
    name: 'deepseek-v3',
    description: 'deepseek-v3'
  },
  {
    id: 'claude-3.7-sonnet',
    name: 'claude-3.7-sonnet',
    description: 'claude-3.7-sonnet'
  },
  {
    id: 'claude-4-sonnet',
    name: 'claude-4-sonnet',
    description: 'claude-4-sonnet'
  },
  {
    id: 'gemini-2.5-pro-preview-05-06',
    name: 'gemini-2.5-pro-preview-05-06',
    description: 'gemini-2.5-pro-preview-05-06'
  }
]

const availableModels = computed(() => {
  return defaultModels
})

// 计算属性
const activeConfigs = computed(() => {
  return apiConfigs.value.filter(config => config.enabled && config.apiKey).length
})

const formatTemperature = (value) => {
  if (value <= 0.3) return '保守'
  if (value <= 0.7) return '平衡'
  return '创新'
}

const getStatusType = (status) => {
  const types = {
    connected: 'success',
    disconnected: 'danger',
    connecting: 'warning',
    error: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    connected: '已连接',
    disconnected: '未连接',
    connecting: '连接中',
    error: '连接错误'
  }
  return texts[status] || '未知'
}

// 方法
const loadApiConfigs = async () => {
  try {
    const configs = await apiConfigApi.getApiConfigs()
    apiConfigs.value = configs.map(config => ({
      ...config,
      testing: false,
      status: config.status || 'disconnected'
    }))
  } catch (error) {
    console.error('加载API配置失败:', error)
    ElMessage.error('加载API配置失败')
  }
}

const addNewConfig = () => {
  isEditing.value = false
  resetForm()
  showConfigDialog.value = true
}

const editConfig = (config) => {
  isEditing.value = true
  Object.assign(configForm, {
    ...config,
    unlimitedTokens: config.maxTokens === null || config.unlimitedTokens,
    enabled: !!config.enabled, // 确保转换为布尔值
    streamMode: !!config.streamMode // 确保转换为布尔值
  })
  showConfigDialog.value = true
}

const resetForm = () => {
  Object.assign(configForm, {
    id: null,
    name: '',
    description: '',
    type: 'custom',
    apiKey: '',
    baseUrl: 'https://api.openai.com/v1',
    selectedModel: 'gpt-3.5-turbo',
    maxTokens: 2000000,
    unlimitedTokens: false,
    temperature: 0.7,
    topP: 1.0,
    frequencyPenalty: 0.0,
    presencePenalty: 0.0,
    timeout: 30,
    streamMode: true,
    retryCount: 3,
    customHeaders: '',
    enabled: true
  })
  if (configFormRef.value) {
    configFormRef.value.clearValidate()
  }
}

const handleUnlimitedTokensChange = () => {
  if (configForm.unlimitedTokens) {
    configForm.maxTokens = null
  } else {
    configForm.maxTokens = 2000000
  }
}

const saveConfig = async () => {
  if (!configFormRef.value) return

  try {
    await configFormRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    const configData = {
      ...configForm,
      maxTokens: configForm.unlimitedTokens ? null : configForm.maxTokens,
      unlimitedTokens: configForm.unlimitedTokens ? 1 : 0,
      streamMode: configForm.streamMode ? 1 : 0,
      enabled: configForm.enabled ? 1 : 0
    }

    if (isEditing.value) {
      await apiConfigApi.updateApiConfig(configForm.id, configData)
      ElMessage.success('配置更新成功')
    } else {
      await apiConfigApi.createApiConfig(configData)
      ElMessage.success('配置创建成功')
    }

    showConfigDialog.value = false
    await loadApiConfigs()
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    saving.value = false
  }
}

const useConfig = async (configId) => {
  try {
    // 切换到此配置
    const success = await store.switchToApiConfig(configId)

    if (success) {
      ElMessage.success('已使用此配置')
      await loadApiConfigs()
    } else {
      ElMessage.error('切换配置失败')
      await loadApiConfigs()
    }
  } catch (error) {
    console.error('使用失败:', error)
    ElMessage.error('使用失败')
  }
}

const toggleConfigStatus = async (config) => {
  try {
    const newStatus = !config.enabled
    const configData = {
      ...config,
      enabled: newStatus ? 1 : 0
    }

    await apiConfigApi.updateApiConfig(config.id, configData)
    ElMessage.success(`配置已${newStatus ? '启用' : '禁用'}`)
    await loadApiConfigs()
  } catch (error) {
    console.error('切换配置状态失败:', error)
    ElMessage.error('切换配置状态失败')
  }
}

const testConnection = async (config) => {
  config.testing = true
  config.status = 'connecting'

  try {
    await apiConfigApi.testApiConfig(config.id)
    config.status = 'connected'
    ElMessage.success(`${config.name} 连接测试成功`)
  } catch (error) {
    config.status = 'error'
    console.error('连接测试失败:', error)
    ElMessage.error(`${config.name} 连接测试失败`)
  } finally {
    config.testing = false
  }
}

const duplicateConfig = async (configId) => {
  try {
    await apiConfigApi.duplicateApiConfig(configId)
    ElMessage.success('配置复制成功')
    await loadApiConfigs()
  } catch (error) {
    console.error('复制配置失败:', error)
    ElMessage.error('复制配置失败')
  }
}

const deleteConfig = async (configId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此配置吗？此操作不可恢复。',
      '删除配置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await apiConfigApi.deleteApiConfig(configId)
    ElMessage.success('配置删除成功')
    await loadApiConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadApiConfigs()
})
</script>

<style scoped>
.api-config {
  padding: 20px;
  max-width: 100%;
}

.config-card {
  max-width: 1600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 配置列表 */
.config-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-item {
  transition: all 0.3s ease;
}

.config-item :deep(.el-card__body) {
  padding: 16px;
}

.config-item.active {
  border-color: #67c23a;
  background: #f0f9ff;
}

.config-item.disabled {
  opacity: 0.6;
  background: #f5f7fa;
}

.config-item.disabled :deep(.el-card__body) {
  background: #f5f7fa;
}

.config-info {
  flex: 1;
}

.config-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  
  margin-bottom: 4px;
}

.config-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.config-actions {
  display: flex;
  flex-direction: row;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.config-details {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.config-detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-detail-item .label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  min-width: 60px;
}

.config-detail-item .value {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

/* 表单样式 */
.max-tokens-control {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .config-item :deep(.el-row) {
    flex-direction: column;
  }
  
  .config-item :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 12px;
  }

  .config-actions {
    flex-direction: row;
    width: 100%;
    justify-content: flex-start;
  }

  .config-details :deep(.el-row) {
    flex-direction: column;
  }
  
  .config-details :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 8px;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-slider__runway) {
  margin: 16px 0;
}

:deep(.el-alert) {
  margin-bottom: 16px;
}
</style>